<?php

namespace App\Services;

use App\Models\Setting;
use Exception;
use Illuminate\Support\Facades\Log;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliVodService
{
    protected $accessKeyId;
    protected $accessKeySecret;
    protected $regionId;
    protected $mockMode = false; // 关闭模拟模式
    protected $debug = false; // 关闭调试模式
    protected $sdkInstalled = false; // 标记SDK是否已安装

    public function __construct()
    {
        // 从设置表读取阿里云访问凭证
        $this->accessKeyId = Setting::where('key', 'ali_access')->value('value');
        $this->accessKeySecret = Setting::where('key', 'ali_secret')->value('value');
        $this->regionId = Setting::where('key', 'ali_region')->value('value') ?: 'cn-shanghai'; // 默认为上海区域
        
        // 检查SDK是否已安装
        $this->sdkInstalled = class_exists('\\AlibabaCloud\\Client\\AlibabaCloud');
        
        if (!$this->sdkInstalled) {
            Log::error('阿里云SDK未安装', [
                'solution' => '请运行 composer require alibabacloud/sdk 安装SDK'
            ]);
        }
        // 验证凭证是否存在
        elseif (empty($this->accessKeyId) || empty($this->accessKeySecret)) {
            Log::error('阿里云VOD配置不完整', [
                'accessKeyId' => empty($this->accessKeyId) ? '未设置' : '已设置',
                'accessKeySecret' => empty($this->accessKeySecret) ? '未设置' : '已设置',
                'regionId' => $this->regionId
            ]);
        } else {
            Log::info('阿里云VOD凭证加载成功', [
                'accessKeyIdLength' => strlen($this->accessKeyId),
                'regionId' => $this->regionId
            ]);
        }
    }

    /**
     * 获取视频播放凭证
     * @param string $videoId 视频ID
     * @return string 播放凭证
     */
    public function getPlayAuth($videoId)
    {
        // 检查SDK是否已安装
        if (!$this->sdkInstalled) {
            Log::error('尝试获取播放凭证失败：阿里云SDK未安装', [
                'videoId' => $videoId,
                'solution' => '请运行 composer require alibabacloud/sdk 安装SDK'
            ]);
            return '';
        }
        
        // 检查配置是否完整
        if (empty($this->accessKeyId) || empty($this->accessKeySecret)) {
            Log::error('尝试获取播放凭证失败：阿里云VOD配置不完整', ['videoId' => $videoId]);
            return '';
        }
        
        try {
            Log::info('开始获取播放凭证', ['videoId' => $videoId, 'regionId' => $this->regionId]);
            
            // 使用阿里云SDK的另一种方式
            // 创建Client
            \AlibabaCloud\Client\AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId($this->regionId)
                ->asDefaultClient();
            
            // 直接使用RPC请求，而不是具体的类
            try {
                $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                    ->product('vod')
                    ->version('2017-03-21')
                    ->action('GetVideoPlayAuth')
                    ->method('POST')
                    ->options([
                        'query' => [
                            'VideoId' => $videoId,
                        ],
                    ])
                    ->request();
                
                // 处理响应
                if (isset($result['PlayAuth'])) {
                    Log::info('成功获取播放凭证', [
                        'videoId' => $videoId,
                        'playAuthLength' => strlen($result['PlayAuth'])
                    ]);
                    
                    return $result['PlayAuth'];
                } else {
                    Log::error('阿里云响应不包含PlayAuth', [
                        'response' => json_encode($result->toArray())
                    ]);
                    return '';
                }
            } catch (ClientException $e) {
                Log::error('阿里云客户端异常', [
                    'videoId' => $videoId,
                    'message' => $e->getMessage(),
                    'code' => $e->getCode()
                ]);
                return '';
            } catch (ServerException $e) {
                Log::error('阿里云服务器异常', [
                    'videoId' => $videoId,
                    'message' => $e->getMessage(),
                    'code' => $e->getCode(),
                    'requestId' => $e->getRequestId()
                ]);
                return '';
            }
        } catch (Exception $e) {
            Log::error('获取播放凭证异常', [
                'videoId' => $videoId,
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return '';
        }
    }

    /**
     * 获取视频播放地址信息
     * @param string $videoId 视频ID
     * @param array $options 可选参数，包括:
     *   - formats: 媒体流格式，多个格式使用逗号分隔，例如：mp4,m3u8
     *   - authTimeout: 播放地址的有效时间(秒)
     *   - streamType: 媒体流类型，可选video或audio
     * @return array|null 返回包含播放地址信息的数组，失败返回null
     */
    public function getPlayInfo($videoId, array $options = [])
    {
        // 检查SDK是否已安装
        if (!$this->sdkInstalled) {
            Log::error('尝试获取播放地址失败：阿里云SDK未安装', [
                'videoId' => $videoId,
                'solution' => '请运行 composer require alibabacloud/sdk 安装SDK'
            ]);
            return null;
        }
        
        // 检查配置是否完整
        if (empty($this->accessKeyId) || empty($this->accessKeySecret)) {
            Log::error('尝试获取播放地址失败：阿里云VOD配置不完整', ['videoId' => $videoId]);
            return null;
        }
        
        try {
            Log::info('开始获取播放地址', ['videoId' => $videoId, 'options' => $options]);
            
            // 创建Client
            \AlibabaCloud\Client\AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId($this->regionId)
                ->asDefaultClient();
            
            // 准备请求参数
            $query = ['VideoId' => $videoId];
            
            // 添加可选参数
            if (!empty($options['formats'])) {
                $query['Formats'] = $options['formats'];
            }
            
            if (!empty($options['authTimeout'])) {
                $query['AuthTimeout'] = $options['authTimeout'];
            }
            
            if (!empty($options['streamType'])) {
                $query['StreamType'] = $options['streamType'];
            }
            
            // 发送请求
            try {
                $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                    ->product('vod')
                    ->version('2017-03-21')
                    ->action('GetPlayInfo')
                    ->method('POST')
                    ->options([
                        'query' => $query,
                    ])
                    ->request();
                
                // 处理响应
                $response = $result->toArray();
                
                if (isset($response['PlayInfoList']) && isset($response['VideoBase'])) {
                    Log::info('成功获取播放地址', [
                        'videoId' => $videoId,
                        'playInfoCount' => count($response['PlayInfoList']['PlayInfo'] ?? [])
                    ]);
                    
                    return $response;
                } else {
                    Log::error('阿里云响应不包含有效播放信息', [
                        'response' => json_encode($response)
                    ]);
                    return null;
                }
            } catch (ClientException $e) {
                Log::error('阿里云客户端异常', [
                    'videoId' => $videoId,
                    'message' => $e->getMessage(),
                    'code' => $e->getCode()
                ]);
                return null;
            } catch (ServerException $e) {
                Log::error('阿里云服务器异常', [
                    'videoId' => $videoId,
                    'message' => $e->getMessage(),
                    'code' => $e->getCode(),
                    'requestId' => $e->getRequestId()
                ]);
                return null;
            }
        } catch (Exception $e) {
            Log::error('获取播放地址异常', [
                'videoId' => $videoId,
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return null;
        }
    }

    /**
     * 验证阿里云VOD配置是否正确
     * @return array 验证结果
     */
    public function validateConfig()
    {
        $result = [
            'status' => false,
            'errors' => []
        ];
        
        // 检查SDK是否已安装
        if (!$this->sdkInstalled) {
            $result['errors'][] = '阿里云SDK未安装，请运行 composer require alibabacloud/sdk 安装SDK';
            return $result;
        }
        
        // 检查凭证是否存在
        if (empty($this->accessKeyId)) {
            $result['errors'][] = 'AccessKeyID未设置，请在settings表中配置ali_access';
        }
        
        if (empty($this->accessKeySecret)) {
            $result['errors'][] = 'AccessKeySecret未设置，请在settings表中配置ali_secret';
        }
        
        if (empty($this->regionId)) {
            $result['errors'][] = '区域ID未设置，使用默认值: cn-shanghai';
        }
        
        // 如果有任何缺失设置，返回失败
        if (!empty($result['errors'])) {
            return $result;
        }
        
        // 尝试创建客户端验证配置
        try {
            // 简单验证配置是否有效
            \AlibabaCloud\Client\AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessKeySecret)
                ->regionId($this->regionId)
                ->asDefaultClient();
            
            // 尝试一个简单的API调用以验证凭证
            try {
                \AlibabaCloud\Client\AlibabaCloud::rpc()
                    ->product('vod')
                    ->version('2017-03-21')
                    ->action('GetCategories') // 这是一个轻量级调用
                    ->method('POST')
                    ->request();
                
                $result['status'] = true;
                return $result;
            } catch (ClientException $e) {
                // 客户端异常，如凭证错误
                $result['errors'][] = '错误信息: ' . $e->getMessage();
                return $result;
            } catch (ServerException $e) {
                // 如果是权限问题，至少凭证格式是对的
                if ($e->getCode() == 'Forbidden.NotAllowedAccess') {
                    $result['errors'][] = '权限问题: 该AccessKey没有足够权限访问VOD服务';
                } else {
                    // 其他服务器端异常，考虑配置基本有效
                    $result['status'] = true;
                }
                return $result;
            }
        } catch (Exception $e) {
            $result['errors'][] = '错误信息: ' . $e->getMessage();
            return $result;
        }
    }
} 